package com.flight.controller;

import com.flight.model.entity.Order;
import com.flight.model.service.BookingService;
import com.flight.model.service.impl.BookingServiceImpl;
import com.flight.util.Constant;
import com.flight.view.MainFrame;
import com.flight.view.OrderManagePanel;
import com.flight.view.components.MessageDialog;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class BookingController {
    private MainFrame mainFrame;
    private String passengerId;
    private FlightSearchController flightSearchController;
    private OrderManagePanel orderManagePanel;
    private BookingService bookingService = new BookingServiceImpl();

    public BookingController(MainFrame mainFrame, String passengerId) {
        this.mainFrame = mainFrame;
        this.passengerId = passengerId;
        initSubComponents();
        bindMainFrameEvents();
        bindBackEvents(); // 单独绑定返回事件
    }

    private void initSubComponents() {
        // 初始化查询航班控制器和订单面板
        flightSearchController = new FlightSearchController(mainFrame, passengerId);
        orderManagePanel = new OrderManagePanel(passengerId);
        bindOrderPanelEvents();
    }

    // 绑定返回主界面事件（核心修复）
    private void bindBackEvents() {
        // 1. 查询航班界面返回主界面
        flightSearchController.getSearchPanel().addBackListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 关键：切换回主界面的面板（假设 MainFrame 有 getMainPanel() 方法返回首页面板）
                mainFrame.setContentPane(mainFrame.getMainPanel());
                mainFrame.validate(); // 刷新界面
                mainFrame.repaint();
            }
        });

        // 2. 我的订单界面返回主界面
        orderManagePanel.addBackListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 同样切换回主界面面板
                mainFrame.setContentPane(mainFrame.getMainPanel());
                mainFrame.validate();
                mainFrame.repaint();
            }
        });
    }

    // 绑定主窗口的查询航班、我的订单按钮事件
    private void bindMainFrameEvents() {
        // 主界面→查询航班
        mainFrame.addSearchListener(e -> {
            mainFrame.setContentPane(flightSearchController.getSearchPanel());
            mainFrame.validate();
        });

        // 主界面→我的订单
        mainFrame.addOrderListener(e -> {
            loadUserOrders();
            mainFrame.setContentPane(orderManagePanel);
            mainFrame.validate();
        });
    }

    // 绑定订单面板的支付/退票事件
    private void bindOrderPanelEvents() {
        orderManagePanel.setOperationActionListener(e -> handleOrderOperation());
    }

    // 处理订单操作（支付/退票）
    private void handleOrderOperation() {
        Order selectedOrder = orderManagePanel.getSelectedOrder();
        if (selectedOrder == null) return;

        int status = selectedOrder.getPayStatus();
        if (status == Constant.ORDER_STATUS_UNPAID) {
            handleOrderPayment(selectedOrder);
        } else if (status == Constant.ORDER_STATUS_PAID) {
            handleOrderRefund(selectedOrder);
        } else {
            MessageDialog.showInfo(orderManagePanel, "该订单已退款，不可操作");
        }
    }

    // 支付订单
    private void handleOrderPayment(Order order) {
        boolean confirm = MessageDialog.showConfirm(
                orderManagePanel,
                "确认支付订单？\n订单号：" + order.getOrderId() + "\n金额：" + order.getOrderAmount() + "元"
        );
        if (confirm && bookingService.payOrder(order.getOrderId())) {
            MessageDialog.showInfo(orderManagePanel, "支付成功！");
            loadUserOrders(); // 刷新订单列表
        } else {
            MessageDialog.showError(orderManagePanel, "支付失败或已取消");
        }
    }

    // 退订订单
    private void handleOrderRefund(Order order) {
        double refundFee = order.getOrderAmount() * 0.2;
        boolean confirm = MessageDialog.showConfirm(
                orderManagePanel,
                "确认退票？\n手续费：" + refundFee + "元\n实际退款：" + (order.getOrderAmount() - refundFee) + "元"
        );
        if (confirm && bookingService.refundOrder(order.getOrderId())) {
            MessageDialog.showInfo(orderManagePanel, "退票成功！");
            loadUserOrders(); // 刷新订单列表
        } else {
            MessageDialog.showError(orderManagePanel, "退票失败或已取消");
        }
    }

    // 加载当前用户的订单
    private void loadUserOrders() {
        List<Order> orders = bookingService.getOrdersByPassengerId(passengerId);
        orderManagePanel.setOrderData(orders);
    }
}

//package com.flight.controller;
//
//import com.flight.model.entity.Order;
//import com.flight.model.service.BookingService;
//import com.flight.model.service.impl.BookingServiceImpl;
//import com.flight.util.Constant;
//import com.flight.view.FlightSearchPanel;
//import com.flight.view.MainFrame;
//import com.flight.view.OrderManagePanel;
//import com.flight.view.components.MessageDialog;
//
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.util.List;
//
//public class BookingController {
//    private MainFrame mainFrame;
//    private String passengerId;
//    private FlightSearchController flightSearchController;
//    private OrderManagePanel orderManagePanel;
//    private BookingService bookingService = new BookingServiceImpl(); // 初始化服务
//
//    public BookingController(MainFrame mainFrame, String passengerId) {
//        this.mainFrame = mainFrame;
//        this.passengerId = passengerId;
//        initSubComponents();
//        bindMainFrameEvents();
//    }
//
//    private void initSubComponents() {
//        flightSearchController = new FlightSearchController(mainFrame, passengerId);
//        orderManagePanel = new OrderManagePanel(passengerId);
//        bindOrderPanelEvents();
//        // 绑定返回主界面事件
//        bindBackEvents();
//    }
//
//    // 新增：绑定返回主界面事件
//    private void bindBackEvents() {
//        // 航班查询界面返回
//        flightSearchController.getSearchPanel().addBackListener(e -> {
//            mainFrame.setContentPane(mainFrame.getContentPane());
//            mainFrame.validate();
//        });
//
//        // 订单管理界面返回
//        orderManagePanel.addBackListener(e -> {
//            mainFrame.setContentPane(mainFrame.getContentPane());
//            mainFrame.validate();
//        });
//    }
//
//    private void bindMainFrameEvents() {
//        // 绑定查询航班按钮事件（使用lambda简化代码）
//        mainFrame.addSearchListener(e -> {
//            mainFrame.setContentPane(flightSearchController.getSearchPanel());
//            mainFrame.validate();
//        });
//
//        // 绑定我的订单按钮事件
//        mainFrame.addOrderListener(e -> {
//            loadUserOrders();
//            mainFrame.setContentPane(orderManagePanel);
//            mainFrame.validate();
//        });
//    }
//
//    private void bindOrderPanelEvents() {
//        orderManagePanel.setOperationActionListener(e -> handleOrderOperation());
//    }
//
//    private void handleOrderOperation() {
//        Order selectedOrder = orderManagePanel.getSelectedOrder();
//        if (selectedOrder == null) return;
//
//        int status = selectedOrder.getPayStatus();
//        if (status == Constant.ORDER_STATUS_UNPAID) {
//            handleOrderPayment(selectedOrder);
//        } else if (status == Constant.ORDER_STATUS_PAID) {
//            handleOrderRefund(selectedOrder);
//        } else {
//            MessageDialog.showInfo(orderManagePanel, "该订单已退款，不可操作");
//        }
//    }
//
//    private void handleOrderPayment(Order order) {
//        boolean confirm = MessageDialog.showConfirm(
//                orderManagePanel,
//                "确认支付订单？\n订单号：" + order.getOrderId() + "\n金额：" + order.getOrderAmount() + "元"
//        );
//        if (confirm && bookingService.payOrder(order.getOrderId())) {
//            MessageDialog.showInfo(orderManagePanel, "支付成功！");
//            loadUserOrders();
//        } else {
//            MessageDialog.showError(orderManagePanel, "支付失败或已取消");
//        }
//    }
//
//    private void handleOrderRefund(Order order) {
//        double refundFee = order.getOrderAmount() * 0.2;
//        boolean confirm = MessageDialog.showConfirm(
//                orderManagePanel,
//                "确认退票？\n手续费：" + refundFee + "元\n实际退款：" + (order.getOrderAmount() - refundFee) + "元"
//        );
//        if (confirm && bookingService.refundOrder(order.getOrderId())) {
//            MessageDialog.showInfo(orderManagePanel, "退票成功！");
//            loadUserOrders();
//        } else {
//            MessageDialog.showError(orderManagePanel, "退票失败或已取消");
//        }
//    }
//
//    private void loadUserOrders() {
//        List<Order> orders = bookingService.getOrdersByPassengerId(passengerId);
//        orderManagePanel.setOrderData(orders);
//    }
//}